package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.config.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;

@Service
public class UploadService {

    //文件上传的路径
    private static final String IMG_FILE_PATH = "E:\\software\\leyou-software\\nginx-1.16.0\\html\\brand-img";
    //文件访问的路径
    private static final String IMG_URL_PATH = "http://image.leyou.com/brand-img/";
    //允许的文件类型
    private static final List ALLOW_IMG_TYPE = Arrays.asList("image/jpeg","image/bmp","image/jpg","image/png");

    @Autowired
    private OSS client;

    @Autowired
    private OSSProperties prop;

    public String uploadFileToNginx(MultipartFile file){

        try {
            if(!ALLOW_IMG_TYPE.contains(file.getContentType())){
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //可以把文件变成流,进行格式判断
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null){
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //指定上传后文件的类型
            String fileName = UUID.randomUUID() + file.getOriginalFilename();
            File filePath = new File(IMG_FILE_PATH);
            //上传文件
            file.transferTo(new File(filePath,fileName));
            return IMG_URL_PATH + fileName;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }

     public Map<String,Object> getSignature() {
         try {
             long expireTime = prop.getExpireTime();
             long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
             Date expiration = new Date(expireEndTime);
             PolicyConditions policyConds = new PolicyConditions();
             policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
             policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

             String postPolicy = client.generatePostPolicy(expiration, policyConds);
             byte[] binaryData = postPolicy.getBytes("utf-8");
             String encodedPolicy = BinaryUtil.toBase64String(binaryData);
             String postSignature = client.calculatePostSignature(postPolicy);

             Map<String, Object> respMap = new LinkedHashMap<>();
             respMap.put("accessId", prop.getAccessKeyId());
             respMap.put("policy", encodedPolicy);
             respMap.put("signature", postSignature);
             respMap.put("dir", prop.getDir());
             respMap.put("host", prop.getHost());
             respMap.put("expire", expireEndTime);
             return respMap;
         } catch (Exception e) {
             throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
         }
     }
}
